import { defineStore } from 'pinia'
import { AppRouteRecordRaw } from '@/types/route'

interface tagsViewState {
  visitedViews: AppRouteRecordRaw[]
  cachedViews: string[]
}

// hideMenu 缓存隐藏菜单路由
const tagRouteFilterName = ['accountInfo']

export const tagsViewStore = defineStore('tagsView', {
  state: (): tagsViewState => ({
    visitedViews: [],
    cachedViews: []
  }),
  actions: {
    addView(view: AppRouteRecordRaw) {
      if (!view.meta.hideMenu || tagRouteFilterName.includes(view.name)) {
        this.addVisitedView(view)
        this.addCachedView(view)
      }
    },
    addVisitedView(view: AppRouteRecordRaw) {
      if (this.visitedViews.some((v) => v.path === view.path)) return
      this.visitedViews.push(
        Object.assign({}, view, {
          title: view.meta.title || 'no-name'
        })
      )
    },
    addCachedView(view: AppRouteRecordRaw) {
      if (this.cachedViews.includes(view.name)) return
      if (!view.meta.ignoreKeepAlive) {
        this.cachedViews.push(view.name)
      }
    },
    delView(name: string) {
      this.delVisitedView(name)
      this.delCachedView(name)
    },
    delVisitedView(name: string) {
      const index = this.visitedViews.findIndex((item) => item.name === name)
      index > -1 && this.visitedViews.splice(index, 1)
    },
    delCachedView(name: string) {
      const index = this.cachedViews.indexOf(name)
      index > -1 && this.cachedViews.splice(index, 1)
    },
    delOthersViews(view: AppRouteRecordRaw) {
      this.delOtherVisitedView(view)
      this.delOtherCachedView(view)
    },
    delOtherVisitedView(view: AppRouteRecordRaw) {
      this.visitedViews = this.visitedViews.filter((v) => {
        return v.meta.affix || v.path === view.path
      })
    },
    delOtherCachedView(view: AppRouteRecordRaw) {
      const index = this.cachedViews.indexOf(view.name)
      if (index > -1) {
        this.cachedViews = this.cachedViews.slice(index, index + 1)
      } else {
        this.cachedViews = []
      }
    },
    delAllViews() {
      this.visitedViews = this.visitedViews.filter((tag) => tag.meta.affix)
      this.cachedViews = []
    },
    resetView() {
      this.visitedViews = []
      this.cachedViews = []
    }
  }
})
